package util

import (
	"com.smyx/cache"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
)

var SLogger *zap.SugaredLogger

func InitDevLogger() {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.TimeKey = "time"
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoder := zapcore.NewConsoleEncoder(encoderConfig)
	var core zapcore.Core
	if "debug" == cache.CfgStruct.LogLevel {
		core = zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), zapcore.DebugLevel)
	} else if "error" == cache.CfgStruct.LogLevel {
		core = zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), zapcore.ErrorLevel)
	} else {
		core = zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), zapcore.InfoLevel)
	}
	logger := zap.New(core, zap.AddCaller())
	SLogger = logger.Sugar()
}

func InitProdLogger() {
	writeSyncer := getLogWriter()
	encoder := getEncoder()
	var core zapcore.Core
	if "debug" == cache.CfgStruct.LogLevel {
		core = zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)
	} else if "error" == cache.CfgStruct.LogLevel {
		core = zapcore.NewCore(encoder, writeSyncer, zapcore.ErrorLevel)
	} else {
		core = zapcore.NewCore(encoder, writeSyncer, zapcore.InfoLevel)
	}
	logger := zap.New(core, zap.AddCaller())
	SLogger = logger.Sugar()
}

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.TimeKey = "time"
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewConsoleEncoder(encoderConfig)
}

func getLogWriter() zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   "./smyx.log", // 日志文件的位置
		MaxSize:    100,          // 在进行切割之前，日志文件的最大大小（以MB为单位）
		MaxBackups: 5,            // 保留旧文件的最大个数
		MaxAge:     30,           // 保留旧文件的最大天数
		Compress:   false,        // 是否压缩/归档旧文件
	}
	return zapcore.AddSync(lumberJackLogger)
}
